package com.yuanlang.web.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * company 重庆源狼软件科技有限责任公司
 * FileName HandshakeInterceptor
 * Package com.yuanlang.web.interceptor
 * Description websocket 拦截器
 * author huangxueqian
 * create 2018-05-18 9:52
 * version V1.0
 */
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    /*
        @Autowired
        private RedisClientTemplate redisClientTemplate ;
    */

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 握手前操作
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        System.out.println("Before Handshake");
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            // 获取session 后期改为session共享使用
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            if (session != null) {
                String access_token = session.getId();
/*                String tsUserStr = redisClientTemplate.get(access_token);
                TsUser tsUser = JSON.parseObject(tsUserStr,TsUser.class);*/
                // 使用的是session id
                //使用userName区分WebSocketHandler，以便定向发送消息
                //String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);
                //logger.info(tsUser.getUserName()+" ------------>login");
                attributes.put("access_token", access_token);
            } else {
                logger.debug("httpsession is null");
            }
        }

        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request,
                               ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception ex) {
        System.out.println("After Handshake");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
